﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Database
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            CoffeeShopEntities1 db = new CoffeeShopEntities1();
            foreach (Coffee c in db.Coffees)
            {
                Item i = (Item)Page.LoadControl("~/Item.ascx");
                i.Text = String.Format("{0}<span class='price'>({1:C})</span>", c.Name, c.Price);
                i.ItemID = c.ID;
                uiContainer.Controls.Add(i);
            }
            //form1.Controls.Add(new LiteralControl("<hr />"));
            foreach (Cake c in db.Cakes)
            {
                Item i = (Item)Page.LoadControl("~/Item.ascx");
                i.Text = String.Format("{0}<span class='price'>({1:C})</span>", c.Name, c.Price);
                i.ItemID = c.ID;
                uiContainer.Controls.Add(i);
            }
            //form1.Controls.Add(new LiteralControl("<hr />"));
            foreach (var item in db.SelectProducts())
            {
                Item i = (Item)Page.LoadControl("~/Item.ascx");
                i.Text = String.Format("{0}<span class='price'>({1:C})</span>", item.Name, item.Price);
                i.ItemID = item.ID;
                uiContainer.Controls.Add(i);
            }
        }

        protected void HandlePlaceOrder(object sender, EventArgs e)
        {
            CoffeeShopEntities1 db = new CoffeeShopEntities1();
            Validate();
            if( !IsValid ) return;
            string username = uiUsername.Text;
            Customer customer = (from cust in db.Customers
                                 where cust.Name == username
                                 select cust).SingleOrDefault();
            if (customer == null)
            {
                customer = new Customer();
                customer.ID = Guid.NewGuid();
                customer.Name = username;
                db.AddToCustomers(customer);
            }
            Order order = new Order();
            order.ID = Guid.NewGuid();
            order.Customer = customer;
            db.AddToOrders(order);
            foreach (Item item in uiContainer.Controls.OfType<Item>())
            {
                if (item.Number == 0) continue;
                OrderItem oi = new OrderItem();
                oi.ID = Guid.NewGuid();
                oi.ItemID = item.ItemID;
                oi.OrderID = order.ID;
                oi.Count = item.Number;
                db.AddToOrderItems(oi);
            }
            db.SaveChanges();
            Response.Redirect(String.Format("Orders.aspx?ID={0}", order.ID.ToString()));
        }
    }
}